package quiz;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Random;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class TakeQuizServlet
 */
@WebServlet("/Take")
public class TakeQuizServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public TakeQuizServlet() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		DataBase db = (DataBase) request.getServletContext().getAttribute("db");
		Quiz quizBeingTaken = db.getQuiz(Integer.parseInt(request.getParameter("quizID")));
		
		boolean practiceMode = false;
		if (request.getParameter("practiceMode") != null && Boolean.parseBoolean(request.getParameter("practiceMode"))) practiceMode = true;
		
		ArrayList<Question> questionsLeft = quizBeingTaken.getQuestions();
		
		request.getSession().setAttribute("quiz", quizBeingTaken);		
		request.getSession().setAttribute("answers", new ArrayList<QuizResponse>());
		request.getSession().setAttribute("runningScore", new Integer(0));
		request.getSession().setAttribute("runningPossibleScore", new Integer(0));
		request.getSession().setAttribute("time", System.currentTimeMillis());
		request.getSession().setAttribute("practiceMode", practiceMode);
		
		if (quizBeingTaken.is_singlePage()){
			request.getSession().setAttribute("questionsLeft", new ArrayList<Question>());

			RequestDispatcher dpatch = request.getRequestDispatcher("show-quiz.jsp");
			dpatch.forward(request, response);
			return;
		}
		
		request.getSession().setAttribute("questionsLeft", questionsLeft);
		response.sendRedirect("Question");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	}

}
